<template>
  <div class="app-container">
    <el-row>
      <el-col :span="24">
        <div class="h_top">
          <div class="bread_title">
            <span v-if="!edit">新增{{ titleText }}</span>
            <span v-else>更新{{ titleText }}</span>
          </div>
          <div class="save_button">
            <div class="buttonBox">
              <el-button type="primary" icon="el-icon-back" size="mini" @click="goBack">返回</el-button>
            </div>
            <div class="buttonBox">
              <el-button type="primary" icon="el-icon-document-checked" size="mini" @click="save">保存</el-button>
            </div>
            <div v-if="edit" class="buttonBox">
              <el-button type="primary" icon="el-icon-document-remove" size="mini" @click="confirmDel">删除</el-button>
            </div>
          </div>
        </div>
      </el-col>
    </el-row>
    <el-row v-loading="loading">
      <el-form ref="form" :model="data" inline :rules="formRules">
        <el-row :gutter="10">
          <el-col :span="4">
            <el-form-item prop="coding">
              <div>编 号</div>
              <el-input v-model="data.coding" size="mini" />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item>
              <div>设备编码</div>
              <el-input v-model="data.equipment_coding" size="mini" />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item prop="equipment_id">
              <div>设备名称</div>
              <v-select-s v-model="data.equipment_id" :query="{add_field: 'coding'}" action="eqList" @change="getWorkshop" />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item>
              <div>车 间</div>
              <el-input v-model="data.workshop_name" size="mini" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item>
              <div>生产线</div>
              <el-input v-model="data.line_name" size="mini" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item>
              <div>工位</div>
              <el-input v-model="data.process_name" size="mini" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item prop="execute_time">
              <div>基准日期</div>
              <el-date-picker v-model="data.execute_time" type="datetime" placeholder="选择日期时间" align="right" value-format="yyyy-MM-dd HH:mm:ss" size="mini" />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item prop="admin_id">
              <div>负责人</div>
              <v-select-s v-model="data.admin_id" action="adminList" />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item prop="period">
              <div>周 期</div>
              <el-input v-model="data.period" size="mini" />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item prop="period_unit">
              <div>周期单位</div>
              <el-select v-model="data.period_unit" size="mini">
                <el-option v-for="(item, periodUnitIndex) in plansPeriodUnit" :key="periodUnitIndex" :value="item.value" :label="item.name" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col v-if="needExpectManHours" :span="4">
            <el-form-item prop="expect_man_minutes">
              <div>预计工时（分钟）</div>
              <el-input v-model="data.expect_man_minutes" size="mini" />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item prop="task_long">
              <div>任务时长（小时）</div>
              <el-input v-model="data.task_long" size="mini" />
            </el-form-item>
          </el-col>
          <el-col v-if="needMonitor" :span="4">
            <el-form-item prop="monitor">
              <div>班长审核</div>
              <el-select v-model="data.monitor" size="mini">
                <el-option v-for="(item, monitorIndex) in plansCheck" :key="monitorIndex" :label="item.name" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col v-if="needEngineer" :span="4">
            <el-form-item prop="engineer">
              <div>工程师审核</div>
              <el-select v-model="data.engineer" size="mini">
                <el-option v-for="(item, engineerIndex) in plansCheck" :key="engineerIndex" :label="item.name" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item prop="halt">
              <div>停 机</div>
              <el-select v-model="data.halt" size="mini">
                <el-option v-for="(item, haltIndex) in plansHalt" :key="haltIndex" :label="item.name" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col v-if="false" :span="4">
            <el-form-item prop="type_id">
              <div>类 型</div>
              <el-select v-model="data.type_id" size="mini">
                <el-option v-for="(item, typeIndex) in plansType" :key="typeIndex" :label="item.name" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col v-if="needOil" :span="4">
            <el-form-item prop="lub_type">
              <div>方 式</div>
              <el-select v-model="data.lub_type" size="mini">
                <el-option v-for="(item, lubIndex) in plansLubType" :key="lubIndex" :label="item.name" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item prop="profession">
              <div>专 业</div>
              <el-select v-model="data.profession" size="mini">
                <el-option v-for="(item, professionIndex) in plansProfession" :key="professionIndex" :label="item.name" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item prop="status">
              <div>状 态</div>
              <el-select v-model="data.status" size="mini">
                <el-option v-for="(item, statusIndex) in plansStatus" :key="statusIndex" :label="item.name" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div v-if="!edit">
        <el-tabs>
          <el-tab-pane label="描述">
            <Tinymce id="content" v-model="data.content" />
          </el-tab-pane>
        </el-tabs>
      </div>
      <div v-else>
        <el-tabs>
          <el-tab-pane>
            <span slot="label">
              任务
              <el-badge class="mark" :value="taskTotal" />
            </span>
            <template>
              <el-table :data="data.taskList" size="medium">
                <el-table-column label="部位" min-width="8%" prop="part" />
                <el-table-column label="项目内容" min-width="33%" prop="param" />
                <el-table-column label="判定标准" min-width="17%" prop="param_detail" />
                <el-table-column label="方法" min-width="9%" prop="task_name" />
                <el-table-column label="测量单位" min-width="8%" prop="task_unit" />
                <el-table-column label="上限值" min-width="9%" prop="max" />
                <el-table-column label="下限值" min-width="8%" prop="min" />
                <el-table-column label="操作" min-width="8%" align="center">
                  <template slot-scope="{row}">
                    <el-button type="danger" size="mini" @click="removeTask(row.id)">删除</el-button>
                  </template>
                </el-table-column>
                <div slot="append" style="overflow: hidden;padding-bottom:5px;">
                  <el-form ref="append_task" :model="taskData" inline class="hf_form append_other_admin" :rules="append_task">
                    <el-row :gutter="10">
                      <el-col :span="2">
                        <el-form-item prop="part">
                          <el-input v-model="taskData.part" size="mini" />
                        </el-form-item>
                      </el-col>
                      <el-col :span="8">
                        <el-form-item prop="param">
                          <el-input v-model="taskData.param" size="mini" />
                        </el-form-item>
                      </el-col>
                      <el-col :span="4">
                        <el-form-item prop="param_detail">
                          <el-input v-model="taskData.param_detail" size="mini" />
                        </el-form-item>
                      </el-col>
                      <el-col :span="2">
                        <el-form-item prop="task_id">
                          <v-select v-model="taskData.task_id" action="tasksList" version="new" />
                        </el-form-item>
                      </el-col>
                      <el-col :span="2">
                        <el-form-item prop="task_unit">
                          <el-input v-model="taskData.task_unit" size="mini" />
                        </el-form-item>
                      </el-col>
                      <el-col :span="2">
                        <el-form-item prop="max">
                          <el-input v-model="taskData.max" size="mini" />
                        </el-form-item>
                      </el-col>
                      <el-col :span="2">
                        <el-form-item prop="min">
                          <el-input v-model="taskData.min" size="mini" />
                        </el-form-item>
                      </el-col>
                      <el-col :span="2" align="center">
                        <el-form-item>
                          <el-button icon="el-icon-upload2" size="mini" @click="appendTask" />
                        </el-form-item>
                      </el-col>
                    </el-row>
                  </el-form>
                </div>
              </el-table>
            </template>
          </el-tab-pane>
          <el-tab-pane>
            <span slot="label">
              执行人
              <el-badge class="mark" :value="memberTotal" />
            </span>
            <template>
              <el-row>
                <el-col :span="24">
                  <el-table :data="data.memberList" size="medium">
                    <el-table-column label="偏好的员工" prop="admin_name" min-width="92%" />
                    <el-table-column min-width="8%" align="center">
                      <template slot-scope="{row}">
                        <el-button type="danger" size="mini" @click="removeMember(row.id)">删除</el-button>
                      </template>
                    </el-table-column>
                    <div slot="append">
                      <el-form ref="append_member" :model="memberData" inline class="hf_form append_other_admin" :rules="append_member">
                        <el-row :gutter="10">
                          <el-col :span="22">
                            <el-form-item prop="admin_id">
                              <v-select-s v-model="memberData.admin_id" />
                            </el-form-item>
                          </el-col>
                          <el-col :span="2" align="center">
                            <el-form-item>
                              <el-button icon="el-icon-upload2" size="mini" @click="appendMember(2)" />
                            </el-form-item>
                          </el-col>
                        </el-row>
                      </el-form>
                    </div>
                  </el-table>
                </el-col>
              </el-row>
            </template>
          </el-tab-pane>
          <el-tab-pane label="描述">
            <el-row :gutter="10">
              <el-col :span="4">
                <div>
                  <span>创建时间日期</span>
                  <el-input v-model="data.create_time" placeholder="创建时间日期" class="mtb10" size="mini" readonly />
                </div>
                <div>
                  <span>创建人</span>
                  <el-input v-model="data.create_admin" placeholder="创建人" class="mtb10" size="mini" readonly />
                </div>
                <div v-if="data.update_time">
                  <div>
                    <span>最近更新</span>
                    <el-input v-model="data.update_time" placeholder="最近更新" class="mtb10" size="mini" readonly />
                  </div>
                  <div>
                    <span>更新者</span>
                    <el-input v-model="data.update_admin" placeholder="更新者" class="mtb10" size="mini" readonly />
                  </div>
                </div>
              </el-col>
              <el-col :span="20">
                <Tinymce id="content" v-model="data.content" />
              </el-col>
            </el-row>
          </el-tab-pane>
          <el-tab-pane v-if="needParts">
            <span slot="label">
              备件
              <el-badge class="mark" :value="partsTotal" />
            </span>
            <template>
              <el-table :data="data.partsList" size="medium">
                <el-table-column label="备品备件" min-width="32%" prop="parts_name" />
                <el-table-column label="物料号" min-width="24%" prop="parts_coding" />
                <el-table-column label="数量" min-width="8%" prop="number" />
                <el-table-column label="当前数量" min-width="8%" prop="parts_number" />
                <el-table-column label="仓库" min-width="16%" prop="store_name" />
                <el-table-column label="操作" min-width="8%" align="center">
                  <template slot-scope="{row}">
                    <el-button type="danger" size="mini" @click="removeParts(row.id)">删除</el-button>
                  </template>
                </el-table-column>
                <div slot="append" style="overflow: hidden;padding-bottom:5px;">
                  <el-form ref="append_parts" :model="partsData" inline class="hf_form append_other_admin" :rules="append_parts">
                    <el-row :gutter="10">
                      <el-col :span="8">
                        <el-form-item prop="parts_id">
                          <v-select-s v-model="partsData.parts_id" action="partsList" :query="{add_field: 'coding'}" @change="getCurrentParts" />
                        </el-form-item>
                      </el-col>
                      <el-col :span="6">
                        <el-form-item prop="param">
                          <el-input disabled size="mini" />
                        </el-form-item>
                      </el-col>
                      <el-col :span="2">
                        <el-form-item prop="number">
                          <el-input v-model="partsData.number" size="mini" />
                        </el-form-item>
                      </el-col>
                      <el-col :span="2">
                        <el-form-item>
                          <el-input v-model="partsData.current_number" size="mini" />
                        </el-form-item>
                      </el-col>
                      <el-col :span="4">
                        <el-form-item>
                          <el-input v-model="partsData.store" size="mini" />
                        </el-form-item>
                      </el-col>
                      <el-col :span="2" align="center">
                        <el-form-item>
                          <el-button icon="el-icon-upload2" size="mini" @click="appendParts" />
                        </el-form-item>
                      </el-col>
                    </el-row>
                  </el-form>
                </div>
              </el-table>
            </template>
          </el-tab-pane>
          <el-tab-pane v-if="needEngineer">
            <span slot="label">
              工程师
              <el-badge class="mark" :value="engineerTotal" />
            </span>
            <template>
              <el-row>
                <el-col :span="24">
                  <el-table :data="data.engineerList" size="medium">
                    <el-table-column label="偏好的员工" prop="admin_name" min-width="92%" />
                    <el-table-column min-width="8%" align="center">
                      <template slot-scope="{row}">
                        <el-button type="danger" size="mini" @click="removeMember(row.id)">删除</el-button>
                      </template>
                    </el-table-column>
                    <div slot="append">
                      <el-form ref="append_member" :model="memberData" inline class="hf_form append_other_admin" :rules="append_member">
                        <el-row :gutter="10">
                          <el-col :span="22">
                            <el-form-item prop="admin_id">
                              <v-select-s v-model="memberData.admin_id" />
                            </el-form-item>
                          </el-col>
                          <el-col :span="2" align="center">
                            <el-form-item>
                              <el-button icon="el-icon-upload2" size="mini" @click="appendMember(1)" />
                            </el-form-item>
                          </el-col>
                        </el-row>
                      </el-form>
                    </div>
                  </el-table>
                </el-col>
              </el-row>
            </template>
          </el-tab-pane>
        </el-tabs>
      </div>
    </el-row>
  </div>
</template>
<script>
import API from '@/api/project1/plan'
import EquipmentApi from '@/api/asset/equipment'
import PartsApi from '@/api/stock/parts'
import Tinymce from '@/components/Tinymce/index'
import VSelect from '@/components/select'
import VSelectS from '@/components/select-search'
import { plansProfession, plansPeriodUnit, plansCheck, plansStatus, plansHalt, plansType, plansLubType } from '@/utils/options'
export default {
  inject: ['addOne', 'update', 'delOne', 'goUrl', 'isEdit'],
  components: {
    Tinymce,
    VSelect,
    VSelectS
  },
  data() {
    return {
      data: {
        cr_admins: {
          name: ''
        },
        status: 1,
        monitor: 2,
        engineer: 2,
        halt: 2,
        lub_type: 1,
        memberList: [],
        engineerList: [],
        partsList: [],
        taskList: [],
        category_id: '',
        workshop_id: ''
      },
      formRules: {
        coding: [
          {
            required: true,
            message: '请填写编号',
            trigger: 'change'
          }
        ],
        equipment_id: [
          {
            required: true,
            message: '请选择设备名称',
            trigger: 'change'
          }
        ],
        execute_time: [
          {
            required: true,
            message: '请选择基准日期',
            trigger: 'change'
          }
        ],
        admin_id: [
          {
            required: true,
            message: '请选择负责人',
            trigger: 'change'
          }
        ],
        period: [
          {
            required: true,
            message: '请填写周期',
            trigger: 'change'
          }
        ],
        period_unit: [
          {
            required: true,
            message: '请选择周期单位',
            trigger: 'change'
          }
        ],
        task_long: [
          {
            required: true,
            message: '任务时长',
            trigger: 'change'
          }
        ],
        profession: [
          {
            required: true,
            message: '专业',
            trigger: 'change'
          }
        ]
      },
      append_member: {
        admin_id: [
          {
            required: true,
            message: '请选择员工',
            trigger: 'change'
          }
        ]
      },
      append_engineer: {
        admin_id: [
          {
            required: true,
            message: '请选择工程师',
            trigger: 'change'
          }
        ]
      },
      append_task: {
        part: [
          { required: true, message: '请选择部位', trigger: 'change' }
        ],
        param: [
          { required: true, message: '请选择项目内容', trigger: 'change' }
        ],
        param_detail: [
          { required: true, message: '请选择判定标准', trigger: 'change' }
        ],
        task_id: [
          { required: true, message: '请选择方法', trigger: 'change' }
        ]
      },
      append_parts: {
        parts_id: [
          { required: true, message: '请选择备件', trigger: 'change' }
        ],
        number: [
          { required: true, message: '请选择数量', trigger: 'change' }
        ]
      },
      taskTotal: 0,
      memberTotal: 0,
      engineerTotal: 0,
      partsTotal: 0,
      memberData: {},
      engineerData: {},
      taskData: {},
      partsData: {},
      edit: false,
      loading: false,
      workshop: '',
      titleText: '',
      needParts: false,
      needMonitor: false,
      needEngineer: false,
      needOil: false,
      needExpectManHours: false,
      category_id: '',
      plansHalt,
      plansProfession,
      plansPeriodUnit,
      plansCheck,
      plansStatus,
      plansType,
      plansLubType
    }
  },
  created() {
    this.index()
  },
  methods: {
    index() {
      this.category_id = this.$route.path.split('/')[2].split('plan')[1]
      const titleArray = ['', '自主点检', '自主维护', '专业维护', '加油润滑', '专业点检']
      this.titleText = titleArray[this.category_id]
      if (this.isEdit()) {
        this.edit = true
        this.info()
      } else {
        this.data.category_id = this.category_id
      }

      // 2自主维护 3专业维护 4润滑
      const needParts = ['3', '4']
      const needMonitor = ['3', '4']
      const needEngineer = ['3', '4']
      const needOil = ['4']
      const needExpectManHours = ['2', '3', '4']

      this.needParts = needParts.includes(this.category_id)
      this.needMonitor = needMonitor.includes(this.category_id)
      this.needEngineer = needEngineer.includes(this.category_id)
      this.needOil = needOil.includes(this.category_id)
      this.needExpectManHours = needExpectManHours.includes(this.category_id)
    },
    confirmDel() {
      const id = this.data.id
      this.delOne(API, id, true)
    },
    info() {
      this.loading = true
      const id = this.$route.params.id
      API.getOne(id).then(response => {
        if (response.data.error_code) {
          this.$alert(response.data.message, '错误', {
            confirmButtonText: '确定',
            callback: () => {
              this.goBack()
            }
          })
        } else {
          this.data = response.data
          this.data.memberList = response.data.plan_member
          this.data.engineerList = response.data.plan_engineer
          this.data.taskList = response.data.plan_task
          this.data.partsList = response.data.plan_parts
          this.memberTotal = response.data.plan_member ? response.data.plan_member.length : 0
          this.engineerTotal = response.data.plan_engineer ? response.data.plan_engineer.length : 0
          this.taskTotal = response.data.plan_task ? response.data.plan_task.length : 0
          this.partsTotal = response.data.plan_parts ? response.data.plan_parts.length : 0

          console.log(response.data)
        }
      }).finally(() => {
        this.loading = false
      })
    },
    save() {
      const thisData = this.data
      const thisForm = this.$refs.form
      this.edit ? this.update(API, thisData, thisForm) : this.addOne(API, thisData, thisForm)
    },
    appendMember(engineer) {
      this.$refs.append_member.validate((valid) => {
        if (valid) {
          const admin_data = {
            plan_id: this.data.id,
            admin_id: this.memberData.admin_id,
            engineer
          }
          API.appendMember(admin_data).then(response => {
            if (response.data.error_code === 1) {
              this.$message({
                message: '添加成功',
                type: 'success'
              })
              this.info()
            } else {
              this.$message.error(response.data.message)
            }
          })
        }
      })
    },
    removeMember(id) {
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        API.removeMember({ id }).then((response) => {
          if (response.data.error_code === 1) {
            this.$message({
              message: '恭喜你，删除成功',
              type: 'success'
            })
            this.info()
          } else {
            this.$message.error(response.data.message)
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    appendTask() {
      this.$refs.append_task.validate((valid) => {
        if (valid) {
          const taskData = this.taskData
          const task_data = {
            'plan_id': this.data.id,
            'part': taskData.part,
            'param': taskData.param,
            'param_detail': taskData.param_detail,
            'task_id': taskData.task_id,
            'task_unit': taskData.task_unit,
            'max': taskData.max,
            'min': taskData.min
          }
          API.appendTask(task_data).then(res => {
            if (res.data.error_code === 1) {
              this.$message({
                message: '添加成功',
                type: 'success'
              })
              this.info()
            } else {
              this.$message.error(res.data.message)
            }
          })
        }
      })
    },
    removeTask(id) {
      const task_data = {
        'id': id
      }
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        API.removeTask(task_data).then((response) => {
          if (response.data.error_code === 1) {
            this.$message({
              message: '恭喜你，删除成功',
              type: 'success'
            })
            this.info()
          } else {
            this.$message.error(response.data.message)
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    appendParts() {
      this.$refs.append_parts.validate((valid) => {
        if (valid) {
          this.partsData.plan_id = this.data.id
          API.appendParts(this.partsData).then(res => {
            if (res.data.error_code === 1) {
              this.$message({
                message: '添加成功',
                type: 'success'
              })
              this.info()
            } else {
              this.$message.error(res.data.message)
            }
          })
        }
      })
    },
    removeParts(id) {
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        API.removeParts({ id }).then((res) => {
          if (res.data.error_code === 1) {
            this.$message({
              message: '恭喜你，删除成功',
              type: 'success'
            })
            this.info()
          } else {
            this.$message.error(res.data.message)
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    getCurrentParts() {
      PartsApi.getOne(this.partsData.parts_id).then(res => {
        this.$set(this.partsData, 'store', res.data.store.name)
        this.$set(this.partsData, 'current_number', res.data.number)
      })
    },
    goBack() {
      const planCategory = this.$route.path.split('/')[2].split('plan')[1]
      this.goUrl(`/project1/plan${planCategory}`)
    },
    getWorkshop() {
      EquipmentApi.getOne(this.data.equipment_id).then(res => {
        this.workshop = res.data.workshop_x.name
        this.data.equipment_coding = res.data.coding
      })
    }
  }
}
</script>
